package com.qf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.entity.Item;
import com.qf.enums.ExceptionInfoEnum;
import com.qf.exception.SsmException;
import com.qf.mapper.ItemMapper;
import com.qf.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.beans.Transient;
import java.util.List;

@Service
@Slf4j
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Override
    public PageInfo<Item> list(String name,Integer page,Integer size) {
        //执行分页分页
        PageHelper.startPage(page,size);
        //执行分页查询
        Example example = new Example(Item.class);
        Example.Criteria criteria = example.createCriteria();
        if(!StringUtil.isEmpty(name)){
            criteria.andLike("name","%"+name+"%");
        }
        List<Item> list = itemMapper.selectByExample(example);
        //将list封装到PageInfo中
        PageInfo<Item> pageInfo = new PageInfo<Item>(list);
        return pageInfo;
    }

    @Override
    @Transient
    public void save(Item item) {
        int count = itemMapper.insertSelective(item);
        if(count!=1){
            log.error("【添加商品】添加商品信息失败，item={}",item);
            throw new SsmException(ExceptionInfoEnum.ITEM_ADD_ERROR);
        }
    }

    @Override
    public Item findItemById(Integer id) {
        Item item = itemMapper.selectByPrimaryKey(id);
        if(item==null){
            log.error("【修改商品】查询商品信息失败，id={}",id);
            throw new SsmException(ExceptionInfoEnum.ITEM_FIND_ERROR);
        }
        return item;
    }

    @Override
    public void deleteById(Integer id) {
        int count = itemMapper.deleteByPrimaryKey(id);
        if(count!=1){
            log.error("【删除商品】删除商品信息失败，id={}",id);
            throw new SsmException(ExceptionInfoEnum.ITEM_DLE_ERROR);
        }
    }

    @Override
    @Transient
    public void update(Item item) {
        int count = itemMapper.updateByPrimaryKey(item);
        if(count!=1){
            log.error("【修改商品】修改商品信息失败，item={}",item);
            throw new SsmException(ExceptionInfoEnum.ITEM_UPDATE_ERROR);
        }
    }


}
